/* global readChaterAllRecord charToUser getChaterAllRecord getCookie location WebIM addChatRecord template handlePicNoNet atob Blob*/
String.prototype.replaceAll = function (FindText, RepText) {
    return findReplace(this,FindText, RepText);
};

function findReplace(text,FindText, RepText){
    var newStr = text.replace(FindText, RepText);
    if (newStr.indexOf(FindText) != -1){
        return findReplace(newStr,FindText,RepText);
    } else {
        return newStr;
    }
}

template.defaults.imports.chatContextFilter = function (text) {
    //过滤头像
    var faceList = ["[):]","[:D]","[;)]","[:-o]","[:p]","[(H)]","[:@]","[:s]","[:$]","[:(]","[:'(]","[:|]","[(a)]","[8o|]","[8-|]","[+o(]","[<o)]","[|-)]","[*-)]","[:-#]","[:-*]","[^o)]","[8-)]","[(|)]","[(u)]","[(S)]",
    "[(*)]","[(#)]","[(R)]","[({)]","[(})]","[(k)]","[(F)]","[(W)]","[(D)]"];
    for (var i = 0;i < faceList.length ; i++){
        if (text.indexOf(faceList[i]) != -1){
            var imgHtml = getFaceByKey(faceList[i]);
            var img = $(imgHtml).css({ display:'inline' });
            var obj = $('<div></div>').append(img);
            text = text.replaceAll(faceList[i],obj.html());
        }
    }

    //过滤发送过来的藏品
    if(text.indexOf('product:::') != -1){
        var productId = text.replace('product:::','');
        $.ajaxSettings.async = false;
        $.post('/antique/api/mallProduct/web/query', {
            /* global getCookie visitUrl*/
            token: getCookie('token'),
            /* global id */
            id: productId
        }, function (result) {
            var html = template('product', result.data);
            text = html;
            $.ajaxSettings.async = true;
        });
    }
    return text;
};

//渲染藏品简要信息
function antiqueInfoShow(productId){
    $.post('/antique/api/mallProduct/web/query', {
        /* global getCookie visitUrl*/
        token: getCookie('token'),
        /* global id */
        id: productId
    }, function (result) {
        var html = template('product', result.data);
        $('#chat-list').append(html);
    });
}

var conn = new WebIM.connection({
    isMultiLoginSessions: WebIM.config.isMultiLoginSessions,
    https: typeof WebIM.config.https === 'boolean' ? WebIM.config.https : location.protocol === 'https:',
    url: WebIM.config.xmppURL,
    heartBeatWait: WebIM.config.heartBeatWait,
    autoReconnectNumMax: WebIM.config.autoReconnectNumMax,
    autoReconnectInterval: WebIM.config.autoReconnectInterval,
    apiUrl: WebIM.config.apiURL,
    isAutoLogin: true
});

//客服显示拨打电话
if (charToUser == 'gjzx_service'){
    $('#service_tel').click(function(){
        window.location.href = "tel:023-60333183";
    }).show();
}

conn.listen({
    onOpened: function (message) { //连接成功回调
        // 如果isAutoLogin设置为false，那么必须手动设置上线，否则无法收消息
        // 手动上线指的是调用conn.setPresence(); 如果conn初始化时已将isAutoLogin设置为true
        // 则无需调用conn.setPresence();      
        //如果有传入产品ID就显示产品信息
        if (productId && productId != ''){
            accepterSend('product:::' + productId);
            antiqueInfoShow(productId);
        } else {
            readChaterAllRecord(charToUser);
            var readChaterList = getChaterAllRecord(charToUser);
            $("#chat-list").append(template('chat-hostory-list', {
                data: readChaterList,
                myPhoto: getCookie('photo')
            }));
            onBindPreviewImage();
        }       
    },
    onClosed: function (message) {}, //连接关闭回调
    onTextMessage: function (msg) { //收到文本消息
        //时间和内容提取
        var sourceMsg = msg.sourceMsg.split('%datetime%');
        msg.datetime = sourceMsg[1]?timestampToTimeZh(parseInt(sourceMsg[1])):getCurDatetime();
        msg.sourceMsg = sourceMsg[0];
        //根据用户id查看用户信息
        getUserChatList(msg.from.replace('hx_', ''), function (userInfo) {
            var reg = new RegExp("(<img.*src=\"\.*?\>)");  //正则表达式
            //匹配查询是否存在图片标签
            msg.nickName = userInfo ? userInfo.name : '';
            msg.photo = userInfo ? userInfo.photo : '';
            //有图片按照图片的方式进行保存
            if(reg.test(msg.sourceMsg)){
                var re = /src="([^"]*)"/g;  //只查找 /ckfinder/userfiles/images/qi_cym.jpg 这段路径
                var arr = re.exec(msg.sourceMsg);
                msg.url = arr[1];
                addChatRecord({
                    type: 2,
                    sourceMsg: msg.sourceMsg,
                    sender: msg.from,
                    accepter: msg.to,
                    isSender: 0,
                    url: msg.url,
                    datetime: msg.datetime,
                    isRead: 1,
                    nickName: msg.nickName,
                    photo: msg.photo
                });
                if (msg.from == charToUser){
                    $("#chat-list").append(template('senderImg', msg));
                    scrollToBottom();
                    onBindPreviewImage();
                }
            } else {
                addChatRecord({
                    type: 1,
                    sourceMsg: msg.sourceMsg,
                    sender: msg.from,
                    accepter: msg.to,
                    accepterName: getCookie('name'),
                    isSender: 0,
                    datetime: msg.datetime,
                    isRead: 1,
                    nickName: msg.nickName,
                    photo: msg.photo
                });
                if (msg.from == charToUser){
                    $("#chat-list").append(template('sender', msg));
                    scrollToBottom();
                }
            }
        });
    },
    onEmojiMessage: function (message) {}, //收到表情消息
    onCmdMessage: function (message) {}, //收到命令消息
    onAudioMessage: function (message) {}, //收到音频消息
    onLocationMessage: function (message) {}, //收到位置消息
    onFileMessage: function (message) {}, //收到文件消息
    onVideoMessage: function (message) {
        var node = document.getElementById('privateVideo');
        var option = {
            url: message.url,
            headers: {
                'Accept': 'audio/mp4'
            },
            onFileDownloadComplete: function (response) {
                var objectURL = WebIM.utils.parseDownloadResponse.call(conn, response);
                node.src = objectURL;
            },
            onFileDownloadError: function () {
                console.log('File down load error.');
            }
        };
        WebIM.utils.download.call(conn, option);
    }, //收到视频消息
    onPresence: function (message) {}, //处理“广播”或“发布-订阅”消息，如联系人订阅请求、处理群组、聊天室被踢解散等消息
    onRoster: function (message) {}, //处理好友申请
    onInviteMessage: function (message) {}, //处理群组邀请
    onOnline: function () {

    }, //本机网络连接成功
    onOffline: function () {}, //本机网络掉线
    onError: function (message) {}, //失败回调
    onBlacklistUpdate: function (list) { //黑名单变动
        // 查询黑名单，将好友拉黑，将好友从黑名单移除都会回调这个函数，list则是黑名单现有的所有好友信息
        console.log(list);
    },
    onReceivedMessage: function (message) {}, //收到消息送达服务器回执
    onDeliveredMessage: function (message) {}, //收到消息送达客户端回执
    onReadMessage: function (message) {

    }, //收到消息已读回执
    onCreateGroup: function (message) {}, //创建群组成功回执（需调用createGroupNew）
    onMutedMessage: function (message) {} //如果用户在A群组被禁言，在A群发消息会走这个回调并且消息不会传递给群其它成员
});

var options = {
    apiUrl: WebIM.config.apiURL,
    user: 'hx_' + getCookie('userId'),
    pwd: '000000',
    appKey: WebIM.config.appkey
};
conn.open(options);

//根据用户id查询用户详细信息
function getUserChatList(userId, callback) {
    $.post('/antique/api/sysUser/query_user_by_userId', {
        userId: userId
    }, function (result) {
        callback(result.data);
    });
}

$('input[name="send-text"]').on('keypress', function (e) {
    var keycode = e.keyCode;
    if (keycode == '13') {
        accepterSend();
        e.preventDefault();
    }
});

//我发送单个文字
function accepterSend(sendText) {
    var text = '';
    if(sendText && sendText != ''){
        text = sendText;
    } else {
        text = $('input[name="send-text"]').val();
    }
    if (!text || text == '') {
        return false;
    }    
    scrollToBottom();
    var id = conn.getUniqueId(); // 生成本地消息id
    var msg = new WebIM.message('txt', id); // 创建文本消息
    $.post('/antique/api/systemOption/query_sys_time',function(result){
        msg.set({
            msg: text + '%datetime%' + result.data.sysTime, // 消息内容
            to: charToUser, // 接收消息对象（用户id）
            roomType: false,
            success: function (id, serverMsgId) {
                console.log('send private text Success');
            },
            fail: function (e) {
                console.log("Send private text error");
            }
        });
        msg.body.chatType = 'singleChat';
        conn.send(msg.body);
        $('input[name="send-text"]').val('');
        
        var curDatetimeStr = timestampToTimeZh(result.data.sysTime);
        if(!(sendText && sendText != '')){
            $("#chat-list").append(template('accepter', {
                sourceMsg: text,
                datetime: curDatetimeStr,
                nickName: getCookie('name'),
                photo: getCookie('photo')
            }));
            addChatRecord({
                type: 1,
                sourceMsg: text,
                accepter: charToUser,
                isSender: 1,
                datetime: curDatetimeStr,
                isRead: 1,
                nickName: getCookie('name'),
                photo: getCookie('photo')
            });
        }
    });
}

$('input[name="send-text"]').keyup(function (event) {

});
$('#goSend').click(function () {
    accepterSend();
});

function getCurDatetime() {
    var date = new Date();
    var year = date.getFullYear(); //获取当前年份   
    var mon = date.getMonth() + 1; //获取当前月份   
    var da = date.getDate(); //获取当前日   
    var day = date.getDay(); //获取当前星期几   
    var h = date.getHours(); //获取小时   
    var m = date.getMinutes(); //获取分钟   
    var s = date.getSeconds(); //获取秒   
    return year + '年' + mon + '月' + da + '日' + ' ' + h + ':' + m + ':' + s;
}

//**dataURL to blob**
function dataURLtoBlob(dataurl) {
    var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {
        type: mime
    });
}

//我单聊发送图片消息
var sendPrivateImg = function (url) {
    var id = conn.getUniqueId(); // 生成本地消息id
    var msg = new WebIM.message('txt', id); // 创建文本消息
    $.post('/antique/api/systemOption/query_sys_time',function(result){
        msg.set({
            msg: '<img url="' + url + '" src="' + url + '?x-oss-process=image/resize,w_500" class="img" width="100%"/>' + '%datetime%' + result.data.sysTime, // 消息内容
            to: charToUser, // 接收消息对象（用户id）
            roomType: false,
            success: function (id, serverMsgId) {
                var curDatetimeStr = timestampToTimeZh(result.data.sysTime);
                $("#chat-list").append(template('accepterImg', {
                    datetime: curDatetimeStr,
                    url: url,
                    nickName: getCookie('name'),
                    photo: getCookie('photo')
                }));
                scrollToBottom();
                addChatRecord({
                    type: 2,
                    accepter: charToUser,
                    isSender: 1,
                    url: url,
                    datetime: curDatetimeStr,
                    isRead: 1,
                    nickName: getCookie('name'),
                    photo: getCookie('photo')
                });
                onBindPreviewImage();
            },
            fail: function (e) {
                console.log("Send private text error");
            }
        });
        msg.body.chatType = 'singleChat';
        conn.send(msg.body);
    });
};

//选择图片
var access_token = '';
$("#photoframe").click(function () {
    $.post('/antique/api/wxApi/getticket', {
        url: window.location.href
    }, function (result) {
        access_token = result.data.access_token;
        wx.config({
            debug: false,
            appId: result.data.appid,
            timestamp: result.data.timestamp,
            nonceStr: result.data.noncestr,
            signature: result.data.signature,
            jsApiList: [
                // 所有要调用的 API 都要加到这个列表中
                'chooseImage',
                'previewImage',
                'uploadImage',
                'downloadImage',
                'getLocalImgData'
            ]
        });
        wx.ready(function () {
            wx.checkJsApi({
                jsApiList: [
                    'chooseImage',
                    'previewImage',
                    'uploadImage',
                    'downloadImage',
                    'getLocalImgData'
                ],
                success: function (res) {
                    //alert(JSON.stringify(res));
                    //alert(JSON.stringify(res.checkResult.getLocation));
                    if (res.checkResult.getLocation == false) {
                        alert('你的微信版本太低，不支持微信JS接口，请升级到最新的微信版本！');
                        return;
                    } else {
                        wxChooseImage();
                    }
                }
            });
        });
        wx.error(function (res) {
            // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
            alert("验证失败，请重试！");
            wx.closeWindow();
        });
    });
});
var images = {
    localId: [],
    serverId: []
};

/* global uploadCount Sortable*/
function wxChooseImage() {
    wx.chooseImage({
        count: 9, // 默认9
        sizeType: ['original'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
            images.localId = res.localIds;
            if (images.localId.length == 0) {
                alert('请先使用 chooseImage 接口选择图片');
                return;
            }
            var i = 0,length = images.localId.length;
            var showImageUrls = '';
            function upload() {
                //图片上传
                wx.uploadImage({
                    localId: images.localId[i],
                    isShowProgressTips: 1,
                    success: function (res) {
                        i++;
                        $.showLoading('上传' + i + '/' + length + '图片中...');
                        var serverId = res.serverId; // 返回图片的服务器端ID                     
                        //通过ajax来将base64数据转换成图片保存在本地
                        $.get('/uploadToOss',{
                            mediaId:serverId,
                            accessToken:access_token
                        },function(data){
                            var url = data.url;
                            sendPrivateImg(url);
                            if (i < length) {
                                upload();
                            } else {
                                $.showLoading('谢谢使用上传完毕!');
                                setTimeout(function() {
                                    $.hideLoading();
                                }, 200); 
                            }
                        });
                    },
                    fail: function (res) {
                        alert(JSON.stringify(res));
                    }
                });
            }
            upload();
        },
        fail: function (res) {
            alert(JSON.stringify(res));
        }
    });
}

/**
 * 滚动条滚到最底部
 **/
function scrollToBottom() {
    window.setTimeout(function () {
        var ele = document.getElementById('chat-content');
        ele.scrollTop = ele.scrollHeight;
    }, 0);
}
window.onload = function () {
    scrollToBottom();
};

//获取原窗口的高度
var originalHeight = document.documentElement.clientHeight || document.body.clientHeight;
window.onresize = function () {
    //键盘弹起与隐藏都会引起窗口的高度发生变化
    var resizeHeight = document.documentElement.clientHeight || document.body.clientHeight;
    if (resizeHeight - 0 < originalHeight - 0) {
        //当软键盘弹起，在此处操作
        scrollToBottom();
    } else {
        //当软键盘收起，在此处操作
        scrollToBottom();
    }
};

document.body.addEventListener('focusin', function(){
    //软键盘弹出的事件处理
    scrollToBottom();
});

document.body.addEventListener('focusout', function(){
    //软键盘收起的事件处理
    scrollToBottom();
    window.scroll(0, 0);
});

$('input,textarea').on('blur', function () {
    window.scroll(0, 0);
}).on('focus', function () {
    resetFaceList();
});

$('#chat-content').click(function(){
    resetFaceList();
});

function resetFaceList(){
    $('.face-list').hide();
    $('.chat-form').css({
        height: '2.8rem'
    });
    $('.type-list').show();
    $('#chat-content').css({ bottom:'2.8rem' });
    scrollToBottom();
}

$('#goFace').click(function () {
    $('.face-list').show();
    $('.chat-form').css({
        height: '3.1rem'
    });
    $('.type-list').hide();
    $('#chat-content').css({ bottom:'3.1rem' });
    scrollToBottom();
});

$('.face-list li').click(function () {
    var key = $(this).attr('key');
    var text = $('input[name="send-text"]').val();
    text = text + key;
    $('input[name="send-text"]').val(text);
});

//根据key获得对应表情的图片信息
function getFaceByKey(key) {
    var img = $('.face-list li[key="' + key + '"]').html();
    return img;
}

//触发图片事件查看信息
function previewImage(currentUrl,images){
    wx.previewImage({
        current: currentUrl, // 当前显示图片的http链接
        urls: images // 需要预览的图片http链接列表
    });
}

//绑定所有图片单击查看大图事件
function onBindPreviewImage(){
    $('.sender .content .msg img,.accepter .content .msg img').unbind('click').bind('click',function(){
        var url = $(this).attr('url');
        var images = [];
        $('.sender .content .msg img').each(function(){
            images.push($(this).attr('url')); 
        });
        $('.accepter .content .msg img').each(function(){
            images.push($(this).attr('url')); 
        });
        previewImage(url,images);
    });    
}